<template>
    <div>
        <wxc-tab-page ref="wxc-tab-page"
                      :tab-titles="tabTitles"
                      :tab-styles="tabStyles"
                      title-type="icon"
                      pan-dist="20"
                      duration="150"
                      :tab-page-height="tabPageHeight"
                      @wxcTabPageCurrentTabSelected="wxcTabPageCurrentTabSelected">
            <list v-for="(v,index) in tabList"
                  :key="index"
                  class="item-container"
                  :style="{ height: (tabPageHeight - tabStyles.height) + 'px' }">

                <refresh class="border-cell" @refresh="loadData(index,'refresh')"
                         :display="refreshing ? 'show' : 'hide'">
                    <loading-indicator style="width: 50px;height: 50px;color: #00c26e;"
                                       class="indicator"></loading-indicator>
                </refresh>
                <cell v-for="(demo,key) in v" class="cell" :key="key">
                    <wxc-pan-item @wxcPanItemPan="wxcPanItemPan">
                        <div class="content speech-content" v-if="demo && demo.sourceType == 'speech'">
                            <div class="item-head">
                                <image @click="getUserInfo(demo)" class="photo" src="root:img/my_photo.png"></image>
                                <div class="item-user-info">
                                    <div class="item-user-name">
                                        <text style="font-size: 28px;font-weight: 800;margin-right: 20px;color:#5f5f5f;">{{demo.sourceUser}}</text>
                                        <text style="font-size: 28px;color:#999999;">{{demo.sectionName}}</text>
                                    </div>
                                    <div>
                                        <text style="font-size: 24px;color:#999999;">{{formatDate(demo.createTime)}}
                                        </text>
                                    </div>
                                </div>
                            </div>
                            <div class="item-content" @click="jumpSpeechDetail" :data-id="demo && demo.id">

                                <text v-if="demo.contentText" class="item-content-t">{{ textContent(demo.contentText)}}</text>

                                <div class="img-row" v-for="(fimg,findex) in imgTypesettingList(demo.contentFileKey)">
                                    <image class="img-ele"
                                           v-for="(ele,eleIndex) in fimg"
                                           :src="ele.thumb"
                                           @click="openWxcLightboxOverlayClicked(findex*3+eleIndex,demo.contentFileKey)"
                                           placeholder="root:img/default_yx.png"></image>
                                </div>


                                <audio-vue v-if="demo.contentType === '1100'" :time="demo.voiceTime"
                                           :audioSrc="vedioUrl(demo.contentFileKey)"></audio-vue>

                                <!--<image :src="demo.contentFileKey"></image>-->
                            </div>
                            <div class="item-footer">
                                <div class="item-footer-area item-footer-left">
                                    <image class="item-footer-i" src="root:img/read_icon.png"></image>
                                    <text class="item-footer-t">阅读({{demo.lookNum ? demo.lookNum:0}})</text>
                                </div>
                                <div class="item-footer-area item-footer-middle">
                                    <image class="item-footer-i" src="root:img/conment_icon.png"></image>
                                    <text class="item-footer-t" @click="showCommentsClicked(index,key,demo.id)">评论({{demo.commentNum}})</text>
                                </div>
                                <div class="item-footer-area item-footer-right">
                                    <image class="item-footer-i" :src="demo.isLike ? 'root:img/liked_icon.png':'root:img/like_icon.png'"></image>
                                    <text :class="['item-footer-t',demo.isLike && 'liked']" @click="addLike(index, key, demo.id, demo.isLike)">赞({{demo.likeNum}})</text>
                                </div>
                            </div>
                        </div>
                        <div class="content article-item-content" v-else >
                            <div class="article-item-content-title" @click="jumpArticleDetail(demo)" :data-id="demo && demo.id">
                                <div style="height: 200px;margin-bottom: 20px;">
                                    <text style="font-size: 36px;">{{demo ? demo.title:''}}</text>
                                </div>
                                <div style="flex-direction: row;">
                                    <text class="item-s-t">{{demo ? demo.sourceUser:''}}</text>
                                    <text class="item-s-t">{{demo ? demo.commentNum:''}}评论</text>
                                    <text class="item-s-t">{{formatDate(demo ? demo.createTime:'')}}</text>
                                    <image v-if="demo && demo.contentFileKey" src="root:img/attachment.png" style="width: 25px;height: 25px;"></image>

                                </div>
                            </div>
                            <div class="article-item-content-img" @click="jumpArticleDetail(demo)" :data-id="demo && demo.id">
                                    <image v-if="demo" v-for="(fimg,findex) in imgList(demo && demo.headImg)" placeholder="root:img/default_yx.png" style="width: 200px;height: 200px;" :src="fimg.thumb"></image>
                            </div>
                        </div>
                    </wxc-pan-item>

                </cell>

                <cell style="height: 100px;width: 750px;"></cell>

                <loading class="loading" @loading="loadData(index,'loadding')" :display="loadinging ? 'show' : 'hide'">
                    <loading-indicator class="loading-indicator"></loading-indicator>
                </loading>
            </list>
        </wxc-tab-page>
        <send-message
                :params="commentsParams"
                :show="commentsShow"
                name="content"
                @closeLayerClicked="closeCommentsLayerClicked"
                :success="commentsSuccess"
                url="/app/yxq/speech/comments/add"></send-message>
    </div>
</template>
<style scoped>

    .img-ele{
        width: 200px;
        height: 200px;
        margin-left: 15px;
        margin-right: 15px;
    }
    .img-row{
        flex-direction: row;
        margin-bottom: 15px;
    }
    .img-panel{
        flex-direction: column;
    }
    .liked {
        color: #01A65A;
    }

    .follow-img {
        width: 200px;
        height: 200px;
        margin-bottom: 10px;
    }
    .follow-content-img {
        margin-top: 24px;
    }
    .speech-img {
        width: 230px;
        height: 230px;
        margin-left: 5px;
        margin-right: 5px;
        margin-bottom: 5px;
        border-width: 1px;
        border-color: #e9e9e9;
    }

    .loading {
        width: 750px;
        display: -ms-flex;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        -webkit-align-items: center;
        -webkit-box-align: center;
        align-items: center;
    }

    .loading-indicator-text {
        color: #888888;
        font-size: 42px;
        text-align: center;
    }

    .loading-indicator {
        margin-top: 16px;
        height: 40px;
        width: 40px;
        color: blue;
    }

    .indicator-text {
        color: #888888;
        font-size: 42px;
        text-align: center;
    }

    .item-s-t {
        font-size: 24px;
        color: #999999;
        margin-right: 20px;
    }

    .article-item-content {
        flex-direction: row;
        padding-top: 32px;

    }

    .article-item-content-img {
        margin-bottom: 32px;
        width: 200px;
    }

    .article-item-content-title {
        flex-direction: column-reverse;
        width: 520px;
        padding-right: 20px;
        height: 268px;
    }

    .item-footer-i {
        width: 34px;
        height: 23px;
        margin-right: 5px;
    }

    .item-footer-t {
        font-size: 25px;
        color: #272727;
    }

    .item-footer-area {
        width: 240px;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }

    .item-footer {
        height: 78px;
        flex-direction: row;
        border-top-width: 1px;
        border-top-color: #f0f0f0;
        margin-top: 20px;
    }

    .item-content-t {
        font-size: 32px;
        color: #272727;
    }

    .item-content {
    }

    .item-user-info {
        flex-direction: column-reverse;
        margin-left: 10px;
    }



    .item-user-name {
        font-size: 30px;
        margin-bottom: 15px;
        font-weight: bold;
        flex-direction: row;
        justify-content: flex-start;
        align-items: flex-start;
    }

    .photo {
        height: 80px;
        width: 88px;
        border-radius: 100px;
        margin-left: 10px;

        border-width: 1px;
        border-color: #717171;
    }

    .item-head {
        flex-direction: row;
        margin-top: 32px;
    }

    .item-container {
        width: 750px;
        background-color: #f2f3f4;
    }

    .border-cell {
        background-color: #f2f3f4;
        width: 750px;
        height: 100px;
        align-items: center;
        justify-content: center;
        border-bottom-width: 1px;
        border-style: solid;
        border-color: #e0e0e0;
    }

    .cell {
        background-color: #ffffff;
    }

    .content {
        width: 750px;
        border-bottom-width: 10px;
        border-bottom-color: #F6F6F6;
        /*align-items: center;*/
        /*justify-content: center;*/
        padding-left: 15px;
        padding-right: 15px;
    }


</style>
<script>
    import {WxcTabPage, WxcPanItem, Utils, BindEnv,WxcLightbox} from 'weex-ui'
    import nw from '../network/nw.js'
    import utils from '../utils/utils.js'
    import audioVue from './audioVue.vue'
    import sendMessage from '../businessComponents/sendMessage.vue'

    import ynav from '../network/nav.js'


    var urlencode = require('urlencode')

    //请求地址列表
    const url = {
        classifyList: 'app/yxq/index/classify',
        indexList: 'app/yxq/index/list',
        detail: '/app/yxq/article/'
    }

    import Config from '../config'

    export default {
        components: {WxcTabPage, WxcPanItem, audioVue,WxcLightbox,sendMessage},

        data: () => ({
            tabTitles: Config.tabTitles,
            tabStyles: Config.tabStyles,
            tabList: [],
            demoList: [],
            refreshing: false,//genx
            loadinging: false,//加载数据
            tabPageHeight: 1334,
            nodesTime: {},
            page: 0,//第几个栏目
            isRefs: [],//是否刷新当前栏目
            slideImage:[],//流瀑布图片集合
            slideIndex:0,
            slideShow:false,
            commentsShow:false,//是否显示发表评论
            commentsParams:{},//发表评论请求参数
            currentCommentsIndex:[]//记录当前评论是那一条数据
        }),

        methods: {

            onLoad(){
                this.tabPageHeight = Utils.env.getPageHeight()
                var self = this
                //加载分类
                nw.postDefine(url.classifyList, {
                    progress: false,
                    success(res) {

                        var tabs = new Array()

                        tabs.push({
                            title: '关注',
                            icon: null,
                            activeIcon: null,
                            activeIcon: null,
                            stat: '',
                            classifyId: 0
                        })


                        for (let i = 0; i < res.length; i++) {
                            var t = res[i]
                            var tab = {
                                title: t.calssifyName,
                                icon: null,
                                activeIcon: null,
                                activeIcon: null,
                                stat: t.stat,
                                classifyId: t.classifyId
                            }
                            tabs.push(tab)
                        }
                        self.tabTitles = tabs
                        self.loadData(0, 'refresh')

                    }
                })
            },
            //点赞
            addLike(index, key, id, isLike) {
                var param = {}
                param.speechId = id
                var url = '/app/yxq/speech/like'
                var self = this
                nw.postDefine(url, {
                    data: param,
                    success(res) {
                        var ele = self.tabList[index][key]
                        Vue.set(ele, 'isLike', isLike ? 0 : 1)
                        Vue.set(ele, 'likeNum', !isLike ? ele.likeNum + 1 : ele.likeNum == 0 ? 0:ele.likeNum - 1)
                    }
                })
            },

            //关闭发表评论
            closeCommentsLayerClicked(show){
                this.commentsShow = false
            },
            //显发表评论弹出框
            showCommentsClicked(index,key,speechId){
                this.currentCommentsIndex =[index,key]
                this.commentsParams = {speechId:speechId}
                this.commentsShow = true
            },
            //成功发表评论回调函数
            commentsSuccess(res){
                var modal = weex.requireModule('modal')
                if(this.currentCommentsIndex.length > 0) {
                    var recordIndex = this.currentCommentsIndex
                    var ele = this.tabList[recordIndex[0]][recordIndex[1]]
                    Vue.set(this.tabList[recordIndex[0]][recordIndex[1]],'commentNum',ele.commentNum == 0 ? 1:ele.commentNum+1)
                }
                this.commentsShow = false
                modal.toast({message:'评论成功'})
            },

            getUserInfo(data){
                ynav.pushParam('root:com/yx/user/userIndex.js',{userId:data.userId})
            },

            loadData(index, type) {

                const self = this
                const tinfo = self.tabTitles[index]

                self.nodesTime[index] = type == 'refresh' ? '' : self.nodesTime[index] ? self.nodesTime[index] : ''
                var formatTime = this.formatDateTime((self.nodesTime[index]))

                var reqData = {
                    articleTime: formatTime,
                    classifyId: tinfo.classifyId ? tinfo.classifyId : null,
                    attention: index == 0 ? 1 : null
                }

                if (type == 'refresh') {
                    self.refreshing = true
                }

                if (type == 'loadding') {
                    self.loadinging = true
                }


                nw.postDefine(url.indexList, {
                    data: reqData,
                    success(res) {
                        if (type == 'refresh') {
                            var lastTime = null

                            for (let i in res) {
                                let v = res[i]
                                if (v && v.createTime) {
                                    lastTime = v.createTime
                                }
                            }
                            self.nodesTime[index] = lastTime
                            Vue.set(self.tabList, index, res)
                            self.refreshing = false
                        } else {
                            var lastTime = null
                            for (let i in res) {
                                let v = res[i]
                                if (v.sourceType === 'speech' && v.contentText) {
                                    v.contentText = urlencode.decode(v.contentText)
                                }


                                if (v && v.createTime) {
                                    lastTime = v.createTime
                                }
                                self.tabList[index].push(v)
                            }
                            self.nodesTime[index] = lastTime
                            self.loadinging = false
                        }

                        self.isRefs[index] = true
                    }
                })
            },

            wxcTabPageCurrentTabSelected(e) {
                this.page = e.page
                if (!this.isRefs[e.page]) {
                    this.loadData(e.page, 'refresh')
                }
            },

            wxcPanItemPan(e, d) {
                if (BindEnv.supportsEBForAndroid()) {
                    this.$refs['wxc-tab-page'].bindExp(e.element)
                } else {

                }

//                var modal = weex.requireModule('modal')
//                modal.alert({message:d})

            },


            //字符串urlencode转字符串
            toGb(data) {
                return unescape(data.replace(/\\u/gi, '%u'))
//                return escape(data).toLocaleLowerCase().replace(/%u/gi,'\\u');
            },

            //时间戳格式为yyyy-mm-dd
            formatDate(timeStamp) {
                var date = new Date()
                date.setTime(timeStamp)
                var y = date.getFullYear()
                var m = date.getMonth() + 1
                m = m < 10 ? ('0' + m) : m
                var d = date.getDate()
                d = d < 10 ? ('0' + d) : d
                return y + '-' + m + '-' + d
            },
            //时间戳格式为yyyy-MM-dd hh:mm:ss
            formatDateTime(timeStamp) {
                if (!timeStamp) {
                    return ''
                }
                var date = new Date()
                date.setTime(timeStamp)
                var y = date.getFullYear()
                var m = date.getMonth() + 1
                m = m < 10 ? ('0' + m) : m
                var d = date.getDate()
                d = d < 10 ? ('0' + d) : d
                var h = date.getHours()
                h = h < 10 ? ('0' + h) : h
                var minute = date.getMinutes()
                var second = date.getSeconds()
                minute = minute < 10 ? ('0' + minute) : minute
                second = second < 10 ? ('0' + second) : second
                return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
            },


            //获取图片瀑布流高度
            autoFollowHeightStyle: function (urls) {

                if (urls === '') {
                    return {height: 0}
                }

                var arr = this.imgList(urls)
                if(arr.length > 0 ) {
                    var index = parseInt(arr.length / 3)

                    var remain = arr.length % 3

                    if (remain > 0) {
                        index += 1
                    }

                    return {height: index * 220}
                }else{
                    return {height: 0}

                }
            },
            //获取图片集合
            imgList(url) {

                if (!url ||url === '') {
                    return []
                }

                var list = url.split(';')

                var arr = new Array()
                for (let i = 0; i < list.length; i++) {
                    var url =
                        arr.push({
                            url:list[i].split(',')[1],
                            thumb:list[i].split(',')[2],
                        })
                }

                return arr
            },

            imgTypesettingList(url){

                if (!url || url === '') {
                    return [];
                }

                var list = url.split(';')

                var arr = []
                var tempArr = []
                var nindex = 0
                // list = [1,2,3,4,5,6,7]
                for (let i = 0; i < list.length; i++) {
                    var url = {
                        url:list[i].split(',')[1],
                        thumb:list[i].split(',')[2],
                    }

                    if (i / 3 == nindex) {
                        tempArr = []
                        arr.push(tempArr)
                        nindex++
                    }
                    tempArr.push(url)

                }
                return arr
            },

            //开启幻灯片
            openWxcLightboxOverlayClicked(findex,url) {


                var arr = this.imgList(url)

                let imgArr = []
                for(let k in arr){
                    var imgs = arr[k]
                    //imgArr.push({src: imgs.url})
                    imgArr.push(imgs.url)
                }
                this.slideImage = imgArr
                this.slideIndex = findex
                var self = this
              /*  setTimeout(() => {
                    self.slideShow = true
                }, 500)*/
                var zm=weex.requireModule('zoomImage')
                let p={}
                p.index=findex
                p.list=imgArr
                zm.show(p)
            },

            wxcLightboxOverlayClicked() {
                this.slideShow = false
            },


            //内容处理
            textContent(content) {

                if (content == undefined || content == null) {
                    return ''
                }
                return content.length > 66 ? (content.substring(0, 60) + '.....') : content
            },
//
            //获取图片集合

            //获取媒体地址
            vedioUrl(keyUrl) {
                var arr = keyUrl.split(',')

                //暂时写死
//                return 'http://www.w3school.com.cn/i/song.ogg'
                return arr[1]
            },

            //跳转文章详情页
            jumpArticleDetail(data) {
                ynav.pushParam('root:com/yx/article/articleDetail.js', data)

            },
            //跳转个人言论详情
            jumpSpeechDetail(event) {
                ynav.pushParam('root:com/yx/speech/speechDetail.js', {id: event.target.attr.dataId})
            }
        },

        mounted() {
            if (weex.config.env.platform.toLowerCase() == 'android') {
               this.onLoad()
            }
        }
    };


</script>